﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Linq;
using System.Threading.Tasks;
using WorkerService.Common;
using WorkerService.Data;
using WorkerService.Model.Send;

namespace WorkerService.Job
{
    [DisallowConcurrentExecution]
    public class SF6Job : IJob
    {
        private readonly ILogger<SF6Job> _logger;
        public SF6Job(ILogger<SF6Job> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// SF6同步作业
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Execute(IJobExecutionContext context)
        {

            _logger.LogInformation("SF6作业开始");

            var time = DateTime.Now.AddHours(-1).ToString("yyyy/MM/dd HH:00:00");

            //SF6全表
            var sql = $"select [name] from sys.tables where [name] like '%SF6%'";
            var data = SqlDBHelper.Query<string>(sql);


            if (data != null && data.Count > 0)
            {
                try
                {


                    for (int i = 0; i < data.Count; i++)
                    {
                        sql = $"select top 1.*  from {data[i]} where  [Time]>'{time}'  order by  [Time] desc ";
                        var sf6List = SqlDBHelper.Query<SF6Model>(sql).FirstOrDefault();
                        if (sf6List!=null)
                        {
                            //取一张表传递一次 

                            var model = new SF6Model();
                            model.TableName = data[i].Split("_")[1];
                            model.Pressure = sf6List.Pressure;
                            model.Moisture = sf6List.Moisture;
                            model.Time = sf6List.Time;
                            model.SiteId = AppConfigurtaionServices.Configuration.GetSection("Site").Value;


                            _logger.LogInformation("SF6数据上传中：" + JsonConvert.SerializeObject(model));

                            HTTPHelper.Client_Post($"{AppConfigurtaionServices.Configuration.GetSection("Send").Value}Client/SF6Accept", JsonConvert.SerializeObject(model), "siteapp.workservice");
                        }
                        
                    }

                }
                catch (Exception e)
                {

                    throw;
                }
            }

            _logger.LogInformation("SF6作业结束");


            return Task.CompletedTask;
        }
    }


}
